<?php

namespace App\Http\Controllers\Admin;

use App\Models\News;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Redirect;

class NewsController extends BaseController
{

    public function index()
    {
//        if(!$this->user->can('viewContentLink'))
//            abort(405);

        $news = News::orderBy('id', 'DESC')->paginate(20);
        return view('admin.news.index')->with('news', $news);
    }

    public function create()
    {
//        if(!$this->user->can('editContentLink'))
//            abort(405);

        return view('admin.news.add');
    }

    public function edit($id)
    {
//        if(!$this->user->can('viewContentPosition'))
//            abort(405);

        $news = News::find($id);
        return view('admin.news.edit')->with('news', $news);

    }

    public function store(Request $request)
    {
//        if(!$this->user->can('editContentLink'))
//            abort(405);

        $id = Input::get('id');
        if ($id > 0)
            $news = News::find($id);
        else
            $news = new News;
        /*处理表单POST来的数据*/
        foreach (array_except(Input::all(), ['_token','id']) as $key => $val) {
            $news->$key = $val;
        }

        if ($news->save()) {
            return redirect("admin/content/news");
        } else {
            return Redirect::back()->withInput()->withErrors('保存失败!');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
//        if(!$this->user->can('deleteContentLink'))
//            return $this->formatJson('error','抱歉，您没有相关权限');

        $news = News::find($id);
        if ($news->delete())
            return  Response::json(array('status'=>'success','msg'=>'新闻 [' . str_limit($news->title, 15, '...') . '] 删除成功'));
        else
            return  Response::json(array('status'=>'error','msg'=>'删除失败'));
    }
}
